﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using qltscd.Helper;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Text;
using System.Web.Routing;

namespace qltscd.Controllers
{
    public class KieuController : BaseController
    {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ActionResult ShowPdf()
        {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucKieu.rpt";
            rpt.Load();
            rpt.SetDatabaseLogon("sa", "sa");
            //rpt.SetDataSource(db.DanhMucKieux);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }



        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucKieux
                       select n;

            myTable.Columns.Add("Mã Kiểu");
            myTable.Columns.Add("Tên Kiểu");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaKieu.ToString(), n.TenKieu.ToString());
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucKieu.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC KIỂU\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch
            {

            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucKieu", "application/ms-excel", "BaoCaoDanhMucKieu.xls");
        }

        public ViewResult Index()
        {
            Session[SessionConstants.ERROR_MESSAGE] = string.Empty;
            KScreenClient screen = new KScreenClient();
            if (Session[SessionScreenContansts.KIEU_SCREENCLIENT] != null)
            {
                screen = (KScreenClient)Session[SessionScreenContansts.KIEU_SCREENCLIENT];
            }
            Search(screen);
            return View(screen);
        }

        /*private void Search(DVQLScreenClient screen)
        {
            throw new NotImplementedException();
        }*/
        [HttpPost]
        public ActionResult Index(KScreenClient screen)
        {
            Search(screen);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index()
        {
            KScreenClient screen = new KScreenClient();
            if (Session[SessionScreenContansts.KIEU_SCREENCLIENT] != null)
            {
                screen = (KScreenClient)Session[SessionScreenContansts.KIEU_SCREENCLIENT];
            }
            Search(screen);
            return View(new GridModel(screen.DSKieu));
        }
        public ActionResult Create()
        {
            ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai");
            ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat");
            Models.BaseClient.DanhMucKieu k = new Models.BaseClient.DanhMucKieu() { IdentityKieu = -1};
            return View(k);
        }

        public ActionResult SuaKieu()
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucKieu k = db.DanhMucKieux.Single(i => i.IdentityKieu == iden);
                Models.BaseClient.DanhMucKieu kC = new Models.BaseClient.DanhMucKieu();
                ObjectHelper.Copy(k, kC);
                ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai", kC.IdentityChungLoai);
                ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat", kC.IdentityHangSanXuat);
                return View(kC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult ThongTinKieu(int id)
        {
            DanhMucKieu k = db.DanhMucKieux.Single(i => i.IdentityKieu == id);
            return View(k);
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult SuaKieu(Models.BaseClient.DanhMucKieu kC)
        {
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucKieu ki = db.DanhMucKieux.Single(i => i.IdentityKieu == kC.IdentityKieu);
                if (kC.MaKieu != ki.MaKieu) {
                    if (db.DanhMucKieux.Count(i => i.MaKieu == kC.MaKieu) > 0) {
                        ViewData[qltscd.Contansts.SessionConstants.ERROR_MESSAGE] = "Mã " + kC.MaKieu + " đã tồn tại";
                        return View(kC);
                    }
                }
                ObjectHelper.Copy(kC, ki);
                db.ObjectStateManager.ChangeObjectState(ki, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai", kC.IdentityChungLoai);
            ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat", kC.IdentityHangSanXuat);
            return View(kC);
        }

        [HttpPost]
        public ActionResult Create(Models.BaseClient.DanhMucKieu danhmuckieu)
        {
            if (ModelState.IsValid)
            {
                DanhMucKieu k = new DanhMucKieu();
                if (danhmuckieu.IdentityKieu == -1)
                {
                    if (db.DanhMucKieux.Count(o => o.MaKieu == danhmuckieu.MaKieu) > 0)
                    {
                        ViewData[SessionConstants.ERROR_MESSAGE] = "Mã kiểu " + danhmuckieu.MaKieu + " đã tồn tại";
                        ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai", danhmuckieu.IdentityChungLoai);
                        ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat", danhmuckieu.IdentityHangSanXuat);
                        return View(danhmuckieu);
                    }
                    ObjectHelper.Copy(danhmuckieu, k);
                    db.DanhMucKieux.AddObject(k);
                }
                else {
                    k = db.DanhMucKieux.Single(i => i.IdentityKieu == danhmuckieu.IdentityKieu);//lấy 1 thằng
                    if (danhmuckieu.MaKieu != k.MaKieu)
                    {
                        if (db.DanhMucKieux.Count(o => o.MaKieu == danhmuckieu.MaKieu) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã kiểu " + danhmuckieu.MaKieu + " đã tồn tại";
                            ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai", danhmuckieu.IdentityChungLoai);
                            ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat", danhmuckieu.IdentityHangSanXuat);
                            return View(danhmuckieu);
                        }
                    }
                    ObjectHelper.Copy(danhmuckieu, k);
                    db.ObjectStateManager.ChangeObjectState(k, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("Create");
            }
            ViewBag.IdentityChungLoai = new SelectList(db.DanhMucChungLoais, "IdentityChungLoai", "TenChungLoai", danhmuckieu.IdentityChungLoai);
            ViewBag.IdentityHangSanXuat = new SelectList(db.DanhMucHangSanXuats, "IdentityHangSanXuat", "TenHangSanXuat", danhmuckieu.IdentityHangSanXuat);
            return View(danhmuckieu);
        }

        public ActionResult Delete(int id)
        {
            DanhMucKieu k = db.DanhMucKieux.Single(i => i.IdentityKieu == id);
            db.DanhMucKieux.DeleteObject(k);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult XoaKieu()
        {
            string id = Request.QueryString["id"];
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucKieu k = db.DanhMucKieux.Single(i => i.IdentityKieu == iden);
                    db.DanhMucKieux.DeleteObject(k);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }


        #endregion

        #region Helper Section
        private void Search(KScreenClient screen)
        {
            if (Session[SessionScreenContansts.KIEU_SCREENCLIENT] != null)
            {
                screen = (KScreenClient)Session[SessionScreenContansts.KIEU_SCREENCLIENT];
            }
            else
            {
                screen = new KScreenClient();
            }
            screen.DSKieu.Clear();
            var list = db.DanhMucKieux.OrderBy(i => i.MaKieu).ToList();
            foreach (DanhMucKieu k in list)
            {
                qltscd.Models.BaseClient.DanhMucKieu kClient = new Models.BaseClient.DanhMucKieu();
                ObjectHelper.Copy(k, kClient);
                kClient.TenChungLoai = k.DanhMucChungLoai.TenChungLoai;
                kClient.TenHangSanXuat = k.DanhMucHangSanXuat.TenHangSanXuat;
                screen.DSKieu.Add(kClient);
            }
            Session[SessionScreenContansts.KIEU_SCREENCLIENT] = screen;
        }
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}